package com.xia.service;

import com.xia.dao.AuthUserMapper;
import com.xia.dao.AuthUserRoleMapper;
import com.xia.entity.AuthUser;
import com.xia.entity.AuthUserExample;
import com.xia.entity.AuthUserRole;
import com.xia.utils.IDUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service
public class UserService {

    private final AuthUserMapper authUserMapper;
    private final AuthUserRoleMapper authUserRoleMapper;

    @Autowired(required = false)
    public UserService(AuthUserMapper authUserMapper, AuthUserRoleMapper authUserRoleMapper) {
        this.authUserMapper = authUserMapper;
        this.authUserRoleMapper = authUserRoleMapper;
    }

    public void addUser(AuthUser authUser) {
        authUser.setId(IDUtils.genItemId());
        this.authUserMapper.insert(authUser);
    }

    public void updateUser(AuthUser authUser) {
        this.authUserMapper.updateByPrimaryKeySelective(authUser);
    }

    public void deleteUserById(Long id) {
        this.authUserMapper.deleteByPrimaryKey(id);
    }

    public List<AuthUser> getUser(String name, String password) {
        AuthUserExample example = new AuthUserExample();
        AuthUserExample.Criteria cri = example.createCriteria();
        cri.andNameEqualTo(name).andPwdEqualTo(password);
        return this.authUserMapper.selectByExample(example);
    }

    public List<AuthUser> getUsers() {
        return this.authUserMapper.selectByExample(new AuthUserExample());
    }

    public List<AuthUser> getUsers(List<Long> ids) {
        AuthUserExample example = new AuthUserExample();
        AuthUserExample.Criteria criteria = example.createCriteria();
        criteria.andIdIn(ids);
        return this.authUserMapper.selectByExample(example);
    }

    @Transactional
    public void addUserRoles(Long userId, Long[] roleIds) {
        for (Long roleId : roleIds) {
            AuthUserRole userRole = new AuthUserRole();
            userRole.setId(IDUtils.genItemId());
            userRole.setUserId(userId);
            userRole.setRoleId(roleId);
            this.authUserRoleMapper.insert(userRole);
        }
    }


}
